package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.PageResult;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 管理员页面分页
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> findPage(int page, int pageSize, String number, String beginTime, String endTime){
        return R.success(orderService.findPage(page,pageSize,number,beginTime,endTime));
    }

    /**
     * 下单提交
     * @param orders
     * @param session
     * @return
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders,HttpSession session) {
        log.info("订单数据：{}", orders);
        User user = (User) session.getAttribute("user");
        orderService.submit(orders,user);
        return R.success("下单成功！");
    }

    /**
     * 移动端用户分页
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page ,int pageSize){
        Page<OrdersDto> dtoPage = orderService.userPage(page,pageSize);
        return R.success(dtoPage);
    }


    /**
     * 再来一单
     * @param map
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Map<String,String> map){
        String ids = map.get("id");

        long id = Long.parseLong(ids);

        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        //获取该订单对应的所有的订单明细表
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);

        //通过用户id把原来的购物车给清空，这里的clean方法是视频中讲过的,建议抽取到service中,那么这里就可以直接调用了
        shoppingCartService.clean();
//        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(ShoppingCart::getId,id);
//        shoppingCartService.remove(wrapper);

        //获取用户id
        Long userId = BaseContext.getCurrentId();

        //把从order表中和order_details表中获取到的数据赋值给这个购物车对象
        //ShoppingCart shoppingCart = new ShoppingCart();

        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item,shoppingCart);
            shoppingCart.setUserId(userId);
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            String dishFlavor = item.getDishFlavor();
            if (dishId != null) {
                //如果是菜品那就添加菜品的查询条件
                shoppingCart.setDishId(dishId);
                shoppingCart.setDishFlavor(dishFlavor);
            } else {
                //添加到购物车的是套餐
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            //shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        shoppingCartService.saveBatch(shoppingCartList);
        return R.success("再来一单");
    }

    /**
     * 派送
     */
//    @PutMapping
//    public R<String> updateOrder(@RequestBody Orders orders){
////        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
//        //orders.setStatus(4);
////        orderService.update(orders);
//        return R.success("订单派送成功");
//
//    }

    @PutMapping
    public R<String> orderStatusChange(@RequestBody Map<String,String> map){
        String id = map.get("id");
        Long orderId = Long.parseLong(id);
        Integer status = Integer.parseInt(map.get("status"));

        if(orderId == null || status == null){
            return R.error("传入信息不合法");
        }
        Orders orders = orderMapper.selectById(orderId);
        orders.setStatus(status);
        orderMapper.updateById(orders);
        return R.success("订单修改成功");
    }
}
